package com.hbu.fleastreet.exceptionhandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.thymeleaf.exceptions.TemplateInputException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by linmm on 2017/12/28.
 * 全局异常处理
 * TODO 后续异常页面展示需优化
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	// 日志记录工具
	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = Exception.class)
	public void handleGlobalException(HttpServletRequest req,HttpServletResponse res, Exception ex)
			throws ServletException, IOException {

		//打印堆栈日志到日志文件中
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		ex.printStackTrace(new java.io.PrintWriter(buf, true));
		String expMessage = buf.toString();
		try {
			buf.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//记录到日志
		log.error("GlobalExceptionHandler,捕获异常:" + ex.getMessage() + ";ExceptionString:" + expMessage);
		req.setAttribute("msg", ex.getMessage());
		req.getRequestDispatcher("/error/500").forward(req, res);
	}

	@ExceptionHandler(value = RuntimeException.class)
	public void runtimeExceptionHandler(HttpServletRequest req, HttpServletResponse res, Exception e) throws Exception {
		//记录日志
		log.error(e.getMessage(), e);
		req.setAttribute("msg", e.getMessage());
		//转发到error页面
		req.getRequestDispatcher("/error/500").forward(req, res);
	}
}
